package com.sh.fmbackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sh.fmbackend.common.ErrorCode;
import com.sh.fmbackend.exception.BusinessException;
import com.sh.fmbackend.mapper.UserMapper;
import com.sh.fmbackend.model.domain.User;
import com.sh.fmbackend.model.request.UserRegisterRequest;
import com.sh.fmbackend.service.UserService;
import com.sh.fmbackend.utils.AlgorithmUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.sh.fmbackend.constant.UserConstant.ADMIN_ROLE;
import static com.sh.fmbackend.constant.UserConstant.USER_LOGIN_STATE;

/**
 * 用户服务实现类
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Resource
    private UserMapper userMapper;

    /**
     * 盐值，混淆密码
     */
    private static final String SALT = "sh";

    @Resource
    private OSSService ossService;

    @Override
    public long userRegister(UserRegisterRequest userRegisterRequest) {
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String email = userRegisterRequest.getEmail();
        String phone = userRegisterRequest.getPhone();
        Integer gender = userRegisterRequest.getGender();
        String userName = userRegisterRequest.getUserName();
        // 1. 校验是否有值
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword, email, phone, userName) || gender == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数有空值");
        }
        // 2. 校验账号
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        }
        // 账户不能包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher userAccountMatcher = Pattern.compile(validPattern).matcher(userAccount);
        if (userAccountMatcher.find()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账户不能包含特殊字符");
        }
        // 密码不能过短
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        // 密码和校验密码是否相同
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码和校验密码不相同");
        }
        // 手机号
        String phonePattern = "^1[3-9]\\d{9}$";
        Matcher phoneMatcher = Pattern.compile(phonePattern).matcher(phone);
        if (!phoneMatcher.matches()){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "手机号格式不正确");
        }

        // qq邮箱
        String emailPattern = "^[1-9][0-9]{4,10}@qq\\.com$";
        Matcher emailMatcher = Pattern.compile(emailPattern).matcher(email);
        if (!emailMatcher.matches()){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "邮箱格式不正确");
        }

        // 账户不能重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        long count = userMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复");
        }

        // todo 用户昵称的敏感词过滤

        // 2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        // 3. 插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setUserName(userName);
        user.setGender(gender);
        user.setPhone(phone);
        user.setEmail(email);
        // 默认头像  用户自己改
        user.setAvatarUrl("http://sh-hengyang.oss-cn-wuhan-lr.aliyuncs.com/friend-match/8.JPG");
        boolean saveResult = this.save(user);
        if (!saveResult) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败");
        }
        return user.getId();
    }


    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        // 1. 校验
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            return null;
        }
        if (userAccount.length() < 4) {
            return null;
        }
        if (userPassword.length() < 8) {
            return null;
        }
        // 账户不能包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            return null;
        }
        // 2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        // 查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("userPassword", encryptPassword);
        User user = userMapper.selectOne(queryWrapper);
        // 用户不存在
        if (user == null) {
            log.info("user login failed, userAccount cannot match userPassword");
            return null;
        }
        // 3. 用户脱敏
        User safetyUser = getSafetyUser(user);
        // 4. 记录用户的登录态
        request.getSession().setAttribute(USER_LOGIN_STATE, safetyUser);
        return safetyUser;
    }

    /**
     * 用户脱敏
     *
     * @param originUser
     * @return
     */
    @Override
    public User getSafetyUser(User originUser) {
        if (originUser == null) {
            return null;
        }
        User safetyUser = new User();
        safetyUser.setId(originUser.getId());
        safetyUser.setUserName(originUser.getUserName());
        safetyUser.setUserAccount(originUser.getUserAccount());
        safetyUser.setAvatarUrl(originUser.getAvatarUrl());
        safetyUser.setGender(originUser.getGender());
        safetyUser.setPhone(originUser.getPhone());
        safetyUser.setEmail(originUser.getEmail());
        safetyUser.setPlanetCode(originUser.getPlanetCode());
        safetyUser.setUserRole(originUser.getUserRole());
        safetyUser.setUserStatus(originUser.getUserStatus());
        safetyUser.setCreateTime(originUser.getCreateTime());
        safetyUser.setTags(originUser.getTags());
        return safetyUser;
    }

    /**
     * 用户注销
     *
     * @param request
     */
    @Override
    public int userLogout(HttpServletRequest request) {
        // 移除登录态
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return 1;
    }


    /**
     * 根据标签列表查询用户
     * 思考点：用sql查询  还是用内存判断   还是结合
     *
     * @param tagNameList
     * @return
     */
    @Override
    public List<User> searchUserByTags(List<String> tagNameList) {
        if (CollectionUtils.isEmpty(tagNameList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "标签列表为空");
        }
        // 查询所有用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        List<User> userList = userMapper.selectList(queryWrapper);  // 所有用户
        // 在内存中判断是否包含要求的标签
        Gson gson = new Gson();
        List<User> collect = userList.stream().filter(user -> {
            String tagsStr = user.getTags();
            // 判断空
            Set<String> tempTagNameSet = gson.fromJson(tagsStr, new TypeToken<Set<String>>() {
            }.getType());
            tempTagNameSet = Optional.ofNullable(tempTagNameSet).orElse(new HashSet<>());
     /*     if (StringUtils.isBlank(tagsStr)) {
                return false;
            }*/
            // 判断是否包含所有的标签
            for (String tagName : tagNameList) {
                if (!tempTagNameSet.contains(tagName)) {
                    return false;
                }
            }
            return true;
        }).map(this::getSafetyUser).collect(Collectors.toList());
        return collect;
    }

    /**
     * 根据标签搜索用户（SQL 查询版）
     *
     * @param tagNameList 用户要拥有的标签
     * @return
     */
//    @Deprecated
    @Override
    public List<User> searchUserByTagsBySQL(List<String> tagNameList) {
        if (CollectionUtils.isEmpty(tagNameList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        // 拼接 and 查询
        // like '%Java%' and like '%Python%'
        for (String tagName : tagNameList) {
            queryWrapper = queryWrapper.like("tags", tagName);
        }
        List<User> userList = userMapper.selectList(queryWrapper);
        return userList.stream().map(this::getSafetyUser).collect(Collectors.toList());
    }

    @Override
    public Integer updateUser(User user, User loginUser) {
        Long userId = user.getId();
        if (userId == null || userId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (!isAdmin(loginUser) && !userId.equals(loginUser.getId())) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        User oldUser = userMapper.selectById(userId);
        if (oldUser == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }

        int result = userMapper.updateById(user);
        if (result < 1) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
        return result;

    }

    /**
     * 获取当前用户信息
     *
     * @param request
     * @return
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        if (request == null) {
            return null;
        }
        User user = (User) request.getSession().getAttribute(USER_LOGIN_STATE);
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        return user;
    }


    @Override
    public boolean isAdmin(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute(USER_LOGIN_STATE);
        if (user == null || user.getUserRole() != ADMIN_ROLE) {
            return false;
        }
        return true;
    }

    @Override
    public boolean isAdmin(User loginUser) {
        if (loginUser == null || loginUser.getUserRole() != ADMIN_ROLE) {
            return false;
        }
        return true;
    }

    @Override
    public List<User> matchUsers(User loginUser, long num) {
        QueryWrapper<User> objectQueryWrapper = new QueryWrapper<>();
        objectQueryWrapper.ne("id", loginUser.getId());
        objectQueryWrapper.isNotNull("tags");
        objectQueryWrapper.select("id", "tags");
        List<User> userList = this.list(objectQueryWrapper);

        String loginUserTags = loginUser.getTags();
        Gson gson = new Gson();
        List<String> loginUserTagSet = gson.fromJson(loginUserTags, new TypeToken<List<String>>() {
        }.getType());

        // 使用最大堆 PriorityQueue 存储最小的前 num 个距离
        PriorityQueue<Map.Entry<Integer, Integer>> maxDistanceQueue = new PriorityQueue<>(
                (a, b) -> b.getValue() - a.getValue()
        );

        for (int i = 0; i < userList.size(); i++) {
            User user = userList.get(i);
            String userTags = user.getTags();
            if (StringUtils.isBlank(userTags)) {
                continue;
            }
            List<String> userTagSet = gson.fromJson(userTags, new TypeToken<List<String>>() {
            }.getType());
            int distance = AlgorithmUtils.minDistance(loginUserTagSet, userTagSet);

            maxDistanceQueue.offer(new AbstractMap.SimpleEntry<>(i, distance));
            if (maxDistanceQueue.size() > num) {
                maxDistanceQueue.poll();
            }
        }

        List<Integer> minDistanceIndexList = maxDistanceQueue.stream()
                .map(Map.Entry::getKey)
                .collect(Collectors.toList());
        // 距离最近的前num个用户的下标
        Collections.reverse(minDistanceIndexList);
        // 取id
        if (CollectionUtils.isEmpty(minDistanceIndexList)){
            return new ArrayList<>();
        }
        List<Long> idList = userList.stream().map(User::getId).collect(Collectors.toList());

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", idList);
        List<User> resUserList = this.list(queryWrapper);

        List<User> res = minDistanceIndexList.stream()
                .map(index -> getSafetyUser(resUserList.get(index)))
                .collect(Collectors.toList());
        return res;
    }

    @Override
    public Boolean updateImg(MultipartFile file, HttpServletRequest request) {
        User loginUser = getLoginUser(request);
        if (loginUser==null|| loginUser.getId()<=0 ){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        User oldUser = this.getById(loginUser.getId());
        if (oldUser == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }

        try {
            String imageUrl = ossService.uploadFile(file);
            oldUser.setAvatarUrl(imageUrl);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        boolean res = this.updateById(oldUser);
        return res;
    }
}




